package com.cjxt.ams.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cjxt.ams.dao.DeptDao;
import com.cjxt.ams.domain.Dept;
import com.cjxt.ams.domain.TreeNode;
import com.cjxt.ams.service.DeptService;
import com.cjxt.ams.utils.R;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.LinkedList;
import java.util.List;


/**
 * @author fangzhiyu
 * @version V1.0
 * @Description: 部门管理 业务层实现类
 * @className: DeptServiceImpl
 * @date 2021/11/19 15:59
 * @company:华勤技术股份有限公司
 * @copyright: Copyright (c) 2021
 */

@Service
public class DeptServiceImpl extends ServiceImpl<DeptDao, Dept> implements DeptService {

    @Resource
    private DeptDao deptDao;

    @Resource
    private DeptService deptService;

    @Override
    public List<Integer> queryDeptIdList(Integer parentId) {
        return baseMapper.queryDeptIdList(parentId);
    }

    @Override
    public List<Dept> queryTree() {
        List<Dept> dept = deptDao.queryTreeData();
        return dept;
    }

    @Override
    public List<TreeNode> treeData() {

        List<TreeNode> list = new LinkedList<>();
        List<Dept> depts = queryTree();
        if (depts != null) {
            for (Dept dept : depts) {
                list.add(new TreeNode(dept.getDeptId(), dept.getName(), dept.getParentId(), null));
            }
        }
        return list;
    }

    @Override
    public List<Dept> queryDeptList(List<Dept> deptList) {
        for (Dept dept : deptList) {
            Integer pid = dept.getParentId();
            if (pid == 0) {
                dept.setParentName("总部");
            } else {
                Dept deptPid = deptDao.selectOne(new QueryWrapper<Dept>().eq("id", pid));
                dept.setParentName(deptPid.getName());
            }
        }
        return deptList;
    }

    @Override
    public R insertDept(Dept dept) {
        if (dept.getParentId() == null) {
            return R.error("ParentId不能为null！！！");
        } else {
            if (getR(dept)) return R.error("已存在该部门！！！");
            deptService.save(dept);
            return R.ok("新增成功");
        }
    }

    @Override
    public R updateDept(Dept dept) {
        if (getR(dept)) return R.error("已存在该部门！！！");
        deptService.updateById(dept);
        return R.ok("新增成功");
    }


    private boolean getR(Dept dept) {
        QueryWrapper<Dept> qw = new QueryWrapper<>();
        QueryWrapper<Dept> eq = qw.eq("parent_id", dept.getParentId()).eq("name", dept.getName());
        if (deptDao.selectCount(eq) > 0) {
            return true;
        }
        return false;
    }
}
